package com.zhdl.hardware.ranging.myantenna.repository.impl;

import com.google.common.eventbus.Subscribe;
import com.project.command.faq.event.behavior.BehaviorPerform;
import com.project.command.instruction.strategy.process.data.AfterStrategyParam;
import com.project.common.util.ByteHelper;
import com.zhdl.common.eventbus.center.EventBusCenter;
import com.zhdl.hardware.ranging.myantenna.repository.MTRangingCmdHandleDao;
import com.zhdl.hardware.robot.borunte.service.impl.BorunteCmdSendServiceImpl;
import com.zhdl.modules.tools.CommonCallback;
import com.zhdl.network.modbus.dto.ModbusDto;
import com.zhdl.network.strategy.common.ProtocolContext;
import com.zhdl.network.strategy.modbusrtu.ModbusRtuStrategy;
import lombok.extern.slf4j.Slf4j;

import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class MTRangingCmdHandleDaoImpl implements MTRangingCmdHandleDao {

    /**
     * 汇川电机-串口
     */
    public String port;
    /**
     * 通信协议处理
     */
    public ProtocolContext protocolContext;
    /**
     * Callback 回调管理
     */
    public Map<String, CommonCallback<byte[]>> commonCallbackMap = new ConcurrentHashMap<>();

    public MTRangingCmdHandleDaoImpl(String port, BehaviorPerform behaviorPerform){
        EventBusCenter.getEventBus().register(this);
        protocolContext = new ProtocolContext(new ModbusRtuStrategy(port, behaviorPerform));
        this.port = port;
    }

    @Subscribe
    public void dataReception(AfterStrategyParam event) {

        /* 判断当前串口 */
        if (port.equals(event.getPortKey())) {
            /* 获取电机指令返回的数据 */
            //此处接收串口或网口客户端回应代码,并处理
            List<ModbusDto> list = event.getNewData();
            ModbusDto modbusDto = list.get(0);

            String instruction = event.getInstruction();
            instruction = instruction.replaceAll(" ", "");
            instruction = instruction.toUpperCase();
            for (String cmd : commonCallbackMap.keySet()) {
                String temp = cmd.toUpperCase();
                if (temp.contains(instruction)) {
                    commonCallbackMap.get(cmd).statusCallback(modbusDto.getUnitBuff());
                    commonCallbackMap.remove(cmd);
                }
            }
        }
    }


    @Override
    public void mtRangingRun(CommonCallback<byte[]> commonCallback){
        String cmd = "0103000F0002F408";
        protocolContext.sendCmd(cmd);
        commonCallbackMap.put(cmd,commonCallback);
    }

}
